var CAMPANAS_URL = 'http://admin.dondereciclo.org/ar/content/campana/';
var mapaController = {

    expandMapComponent: {
	defs: {
	    load: false,
	    mapContainer: $('#mapa-container'),
	    markerDetailsContainer: $('#marker-details-container'),
	    elementsNoExpand: $('#marker-details-container, #informacion-container, #footer, #botonera'),
	    elementsExpand: $('#mapa-box, #markers-list, #scrollbar, #category-list-container, .viewport')
	},

	bind: function(){
	    var self = this;
	    var alto = window.innerHeight - 142;
	    $('#btn-expand-mapa').toggle(
		function () {
		    self.defs.elementsExpand.css({
			height:alto-4
		    });
		    self.defs.elementsNoExpand.hide();
		    self.defs.mapContainer.addClass('expanded-map');
		    google.maps.event.trigger(mapaController.map.defs.map, "resize");
		},
		function () {
		    self.defs.elementsExpand.attr('style', '');
		    self.defs.elementsNoExpand.show();
		    self.defs.mapContainer.removeClass('expanded-map');
		    google.maps.event.trigger(mapaController.map.defs.map, "resize");
		}
		)
	    $(window).resize(function () {
		alto = window.innerHeight - 142;
		if (self.defs.mapContainer.hasClass('expanded-map')) {
		    self.defs.elementsExpand.css({
			height:alto-4
		    });
		}
	    })
	},

	init: function(){
	    if (window.innerWidth > 767) this.bind();
	}
    },

    scrollToComponent: {
	defs: {
	    load: false
	},

	load: function(){
	    var componentsPath = scriptsController.defs.baseUrl+scriptsController.defs.componentsPath+'scrollto/',
	    self = this;

	    $.getScript(componentsPath+'jquery.scrollTo-1.4.2-min.js', function(){
		self.defs.load = true;
		self.bind();
	    });
	},

	bind: function(){
	    var top;
	    $('.scroll-to').die('click').live('click', function(e){
		e.preventDefault();
		top = ($($(this).attr('href')).position().top);
		if (top < 200) {
		    top = 0;
		} else {
		    top = top-100;
		}
		$.scrollTo(top, 800);
	    });

	    if (window.innerWidth < 768) {
		var mapContentPos = $('#mapa-content').position();

		$('.category-list .link').die('click').live('click', function(e){
		    e.preventDefault();
		    top = ((mapContentPos).top)-40;
		    $.scrollTo(top, 800);
		});

		$('.back-to-map').die('click').live('click', function(e){
		    e.preventDefault();
		    top = ((mapContentPos).top)-40;
		    $.scrollTo(top, 800);
		});
	    }
	},

	init: function(){
	    if (!!!this.defs.load) this.load();
	}
    },

    markersListComponent: {
	defs: {
	    container: $('#markers-list-container')
	},

	scrollContent: {
	    defs: {
		load: false
	    },

	    load: function(){
		var componentsPath = scriptsController.defs.baseUrl+scriptsController.defs.componentsPath+'hammer/',
		self = this;

		$.getScript(componentsPath+'hammer.js', function(){
		    self.defs.load = true;
		    self.bind();
		});
	    },

	    bind: function(){

		/**
                 *  TODO: Reemplazar hammer por el iScroll
                 **/

		function TouchScroll(container, options) {
		    container = $(container);
		    var content = $(">.content", container);
		    var scrollbar = $(">.scrollbar div", container);

		    var self = this;
		    var hammer = new Hammer(container.get(0), {
			drag: true,
			drag_vertical: true,
			drag_horizontal: true,
			drag_min_distance: 0,

			transform: false,
			tap: false,
			tap_double: false,
			hold: false
		    });


		    function getScrollPosition() {
			return {
			    top: parseInt(content.css('top'), 10),
			    left: parseInt(content.css('left'), 10)
			};
		    }


		    /**
		     * get the dimensions of a element
		     * @param   jQuery  el
		     * @return  object  { width: int, height: int }
		     */
		    function getDimensions( el ) {
			return {
			    width: el.outerWidth(),
			    height: el.outerHeight()
			};
		    }


		    /**
		     * scroll to given x and y
		     * @param   int x
		     * @param   int y
		     */
		    this.scrollTo = function(x, y)
		    {

		    };


		    var scroll_start = {};
		    var scroll_dim = {};
		    var content_dim = {};

		    hammer.ondragstart = function() {
			scroll_start = getScrollPosition();
			scroll_start.time = new Date().getTime();

			scroll_dim = getDimensions( container );
			content_dim = getDimensions( content );

			scrollbar.css({
			    height: (100 / content_dim.height * scroll_dim.height) * (scroll_dim.height/100)
			}).stop().fadeTo(80, 1);
		    };


		    hammer.ondrag = function( ev ) {
			if(ev.direction == 'up' || ev.direction == 'left') {
			    ev.distance = 0-ev.distance;
			}

			var delta = 1;

			var top = scroll_start.top+ev.distance * delta;
			content.css({
			    top: top
			});

			scrollbar.css({
			    top: (100 / content_dim.height) * (0 - top) +"%"
			});
		    };


		    hammer.ondragend = function( ev ) {
			var scroll = getScrollPosition();
			var corrections = {};
			if(scroll.top > 0) {
			    corrections.top = 0;
			}

			else if(scroll.top < -(content_dim.height - scroll_dim.height) ) {
			    corrections.top = -(content_dim.height - scroll_dim.height);
			}

			content.animate(corrections, 400);
			scrollbar.stop().animate({
			    top: (100 / content_dim.height) * (0 - corrections.top) +"%"
			}, 400);

			scrollbar.stop().fadeTo(80, 0);

		    };
		}

		function tryToBind() {
		    if (!!$('.overflow').length) {
			var scroll = new TouchScroll('.overflow');
			scroll.scrollTo(0, 200);
		    } else {
			setTimeout(tryToBind, 800);
		    }
		}

		tryToBind();
	    },

	    init: function(){
		if (!this.defs.load && window.width < 767) this.load();
	    }
	},

	collapse: {
	    defs: {
		active : true,
		arrows : ['icon-arrow-left', 'icon-arrow-right']
	    },

	    bind: function(){
		var self = this, width, active, arrow, current, container = mapaController.markersListComponent.defs.container;

		container.find('#btn-expand-markers-list').click(function(e){
		    e.preventDefault();
		    current = $(this);
		    var width = '-252px';

		    if (window.innerWidth <= 767) {
			width = '-'+(window.innerWidth - 38)+'px'
		    }

		    if (self.defs.active) {
			width = width;
			active = false;
			arrow = self.defs.arrows[1];
		    } else {
			width = 0;
			active = true;
			arrow = self.defs.arrows[0];
		    }

		    container.animate({
			left: width
		    }, 500, function() {
			self.defs.active = active;
			current.removeClass('icon-arrow-left').removeClass('icon-arrow-right').addClass(arrow)
		    });
		});
	    },

	    init: function(){
		this.bind();
	    }
	},

	init: function(){
	    this.collapse.init();
	    this.scrollContent.init();
	}
    },

    getContent: {
	defs: {
	    infoCategoryDetailsContainer: $('#info-category-details-container'),
	    infoCategoryList: $('#info-category-list'),
	    infoCategoryListContainer: $('#info-category-list-c'),
	    categoryListContainer: document.createElement('div'),
	    categoryList: $('#category-list'),
	    defaultCategoryId: '1',
	    infoContent: []
	},

	get: function(){
	    var self = this;
	    $.ajax({
		url:scriptsController.defs.baseUrl+'controllers/categoriaController/findAll',
		success: function (data) {
		    self.defs.infoContent = data;
		    if (data){
			mapaController.sliderBox.init();
			self.print();
			self.printCategoryInfo(self.defs.defaultCategoryId);
			mapaController.map.init(data['categorias']);
		    }
		}
	    })
	},

	getCssClass: function(id){
	    return this.defs.infoCategoryList.find('[data-category-id="'+id+'"]').attr('class').split(' ')[1];
	},

	setActive: function(id){
	    var container = this.defs.infoCategoryList;
	    container.find('li .link').removeClass('active');
	    container.find('[data-category-id="'+id+'"] .link').addClass('active');
	},

	print: function () {
           
	    var items = this.defs.infoContent,
	    infoCategoryList = this.defs.infoCategoryList,
	    categoryListTpl = document.getElementById('categoryListTpl').value,
	    infoCategoryListTpl = document.getElementById('infoCategoryListTpl').value,
	    item  = '', categoryListContent = '', infoCategoryListContent = '';

	    for (var x in items['orden']) {
		item = items['categorias'][items['orden'][x]];
		categoryListContent += categoryListTpl;
		categoryListContent = categoryListContent.replace(/\$\{categoriaIdentificador\}/g, item.identificador)
		.replace(/\$\{categoriaId\}/g, item.id)
		.replace(/\$\{categoriaNombre\}/g, item.nombre)
		.replace(/\$\{jsOnclick\}/g, 'javascript:mapaController.map.bind(this); return false')
		.replace(/\$\{baseUrl\}/g, scriptsController.defs.baseUrl)
		.replace(/\$\{[a-zA-Z]+\}/g, '');

		infoCategoryListContent += infoCategoryListTpl
		infoCategoryListContent = infoCategoryListContent.replace(/\$\{categoriaIdentificador\}/g, item.identificador)
		.replace(/\$\{categoriaId\}/g, item.id)
		.replace(/\$\{categoriaNombre\}/g, item.nombre)
		.replace(/\$\{[a-zA-Z]+\}/g, '');
	    }
	    $(mapaController.sliderBox.defs.categoryListContainer).find('ul').append(categoryListContent)
	    //mapaController.sliderBox.defs.categoryListContainer.getElementsByTagName('ul')[0].innerHTML = categoryListContent;
	    infoCategoryList.append(infoCategoryListContent);
	},

	printCategoryInfo: function(id){
	    var items = this.defs.infoContent,
	    container = this.defs.infoCategoryDetailsContainer,
	    content = '' , itemClass = '', item;
	    item = items['categorias'][id];
	    itemClass = this.getCssClass(parseInt(item.id));

	    content +=  '<div data-category-id="'+parseInt(item.id)+'" class="'+ itemClass +' box-info">'
	    +'<h3>'+item.nombre+'</h3>'
	    +item.texto
	    +'</div>';

	    container.append(content);
	    this.switcher(id);
	},

	switcher: function(id){
	    var container = this.defs.infoCategoryDetailsContainer;
	    container.find('.box-info').hide();
	    container.find('[data-category-id="'+id+'"]').show();
	    this.setActive(id);
	},

	check: function(id){
	    var self = this,
	    container = self.defs.infoCategoryDetailsContainer;
	    id = parseInt(id);

	    if (!!container.find('[data-category-id='+id+']').length) {
		self.switcher(id)
	    } else {
		self.printCategoryInfo(id);
	    }
	},

	bind: function(){
	    var self = this;
	    $('#info-category-list li a').die('click').live('click', function(e){
		e.preventDefault();
		self.check($(this).parents('.list-item').attr('data-category-id'));
	    });
	},

	init: function(){
	    this.get();
	    this.bind();
	}
    },

    map: {
	defs:{
            //center: new google.maps.LatLng(-33.437778, -70.650278), //Santiago
	    center: new google.maps.LatLng(-34.603526, -58.381586), //Buenos Aires
	    map: null,
	    mapContainer: document.getElementById("mapa-box"),
	    categorias: [],
	    idsCategorias: [],
	    pointsImages: scriptsController.defs.baseUrl+'resources/img/markers/',
	    options: {
		zoom: 13,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
                disableDefaultUI: true,
                zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL
                }
	    },
	    baseUrl: scriptsController.defs.baseUrl,
	    markerDetailsContainer: document.getElementById('marker-details-container'),
	    categoryListContainer: '',
	    urlMarker: false,
	    lastCategoryActive: ''
	},

	setCategorias: function (categorias) {
	    for (var i in categorias) {
		var cat = new Categoria ();
		cat.nombre = categorias[i]['nombre']
		cat.identificador = categorias[i]['identificador']
		this.defs.categorias[i] = cat;
		this.defs.idsCategorias[categorias[i]['identificador']] = i;
	    }
	},

	dynamicUrlParser: function () {
	    var url = document.location+'', id = 0;

	    url = url.replace(this.defs.baseUrl+'mapa', '')
	    .replace('#!/', '')
            .replace(/^\//, '')
	    .replace(/\/$/, '');

	    if (url.indexOf('recicladora/') != -1) {
		var self = this, params = '';
		this.defs.urlMarker = true;
		url = url.replace('recicladora/', '');
		params = url.split('/');
                document.getElementById('markerId').value = params[2];
                $.ajax({
                    url:this.defs.baseUrl+'controllers/markerController/find/'+params[2],
                    success:function (data) {
                        var idCategoria = self.defs.idsCategorias[params[1]];
                        self.defs.map.panTo(new google.maps.LatLng(data.latitud, data.longitud));
                        self.cargarXML(idCategoria, params[2]);
                        $('#categoria'+idCategoria).addClass('active');
                        mapaController.getContent.check(idCategoria)
                    }
                })
	    } else {
		var categorias = url.split('/');
                if (!!categorias[0]) {
                    for (var i in categorias) {
                        id = this.defs.idsCategorias[categorias[i]]
                        this.cargarXML(id);
                        $('#categoria'+id).addClass('active');
                    }
                    this.defs.lastCategoryActive = id;
                    mapaController.getContent.check(id)
                }
		
	    }
	},

	cargarXML: function (categoria, markerId) {
	    var self = this;

	    $.ajax({
		url:self.defs.baseUrl+'controllers/markerController/findByCategoria/'+categoria,
		success:function (xml) {
		    var id, nombreUrl, nombre, direccion, categoriasToString, imagen, web,
		    href, punto, html, marker, current, items = $(xml).find('marker'), item;
		    
		    for (var x = 0, l = items.length; x < l; x++) {
			item = items[x];
			id = item.getAttribute('id');
			nombreUrl = item.getAttribute('nombreUrl');
			nombre = item.getAttribute('nombre');
			direccion = item.getAttribute('direccion');
			categoriasToString = item.getAttribute('categoriasToString');
			imagen = item.getAttribute('imagen');
			web = (item.getAttribute('web')) ? item.getAttribute('web') : '';
			href = (web.indexOf('http') == -1) ? 'http://' + web : web;
			punto = new google.maps.LatLng(
			    parseFloat(item.getAttribute('lat')),
			    parseFloat(item.getAttribute('lng'))
			    );
			html = '<p><b>' + item.getAttribute('nombre') + '</b></p>'
			+ item.getAttribute('comentario')+'<br/>'
			+ item.getAttribute('direccion')+'<br/>'
			+ item.getAttribute('telefono')
			+ '<p><a href="' + href + '" target="_blank">' + web.replace('http://', '') + '</a></p>';
			
			marker = new google.maps.Marker({
			    map: self.defs.map,
			    position: punto,
			    icon: self.defs.pointsImages+imagen + '.png',
			    shadow: self.defs.pointsImages + 'sombra.png',
			    id: id,
			    nombreUrl: nombreUrl,
			    nombre: nombre,
			    direccion: direccion,
			    imagen: imagen,
			    categoriasToString: categoriasToString
			});

			self.defs.categorias[categoria].markers[id] = marker;
			self.bindMarker(marker);
		    }
		    if (markerId != undefined) {
			marker = self.defs.categorias[categoria].markers[markerId];

			marker.infobox.open(self.defs.map, marker);
			mapaController.infobox.currentInfobox = marker.infobox;
			self.mostrarDetallesMarker(marker)
		    }
		}
	    });
	},

	//agrega los listeners a los markers para que cuando se
	//cliqueen se habra el globo con la info
	bindMarker: function (marker) {
	    var self = this;

	    google.maps.event.addListener(marker, 'click', function() {
		self.changeUrlBymarker(marker)
		self.mostrarDetallesMarker(marker)
		$.scrollTo('#marker-details-container',800,{
		    offset:-45
		})
	    });
	    mapaController.infobox.bindMarker(self.defs.map, marker);
	},

	bind: function (target) {
	    target = $(target);
	    var self = this, categoria = target.attr('id').slice(9);

	    target.toggleClass('active');
	    if ($('#category-list .active').size() == 0) {
		alert('Tenes que elegir por lo menos una categoria');
		target.toggleClass('active');
	    } else {
		if (target.hasClass('active')) {
		    if (window.innerWidth <= 767) {
			this.mostrarMarkers(categoria);
			if (!!self.defs.lastCategoryActive) {
			    this.ocultarMarkers(self.defs.lastCategoryActive);
			}
			self.defs.lastCategoryActive = categoria;
		    } else {
			this.mostrarMarkers(categoria);
		    }
		} else {
		    this.ocultarMarkers(categoria);
		}
	    }
	    this.actualizarHash();
	},

	//Funciones para agregar y quitar markers desde el un array
	//las funciones comprueban si el array ya esta cargado con los markers
	//si es asi, usan el array, sino, hacen la llamada ajax para treer
	//los markers, luego los cargan en un array
	mostrarMarkers: function (categoria) {
	    if (this.defs.categorias[categoria].markers.length) {
		for (n in this.defs.categorias[categoria].markers) {
		    this.defs.categorias[categoria].markers[n].setMap(this.defs.map);
		}
	    } else {
		this.cargarXML(categoria);
	    }
	    mapaController.getContent.check(categoria);
	},

	ocultarMarkers: function (categoria) {
	    if (this.defs.categorias[categoria].markers.length) {
		for (n in this.defs.categorias[categoria].markers) {
		    this.defs.categorias[categoria].markers[n].setMap(null);
		}
	    } else {
		this.cargarXML(categoria);
	    }
	    var id = $(mapaController.sliderBox.defs.categoryListContainer).find('.list-item a.active:last').attr('id').replace(/categoria/g, '')
	    mapaController.getContent.check(id)
	},

	mostrarDetallesMarker: function (marker) {
            $('meta[property="og:url"]').attr('content',window.document.location);
            mapaController.tallyCounter.addVisitante(marker.id);
	    $('#marker-details-container header').show();
	    scriptsController.loader.append($('#marker-details-container header .wait'), 'tiny');
	    var self = this,
	    detallesMarkerTpl = document.getElementById('detallesMarkerTpl').innerHTML;
	    $.ajax({
		url:self.defs.baseUrl+'controllers/markerController/detalles/'+marker.id,
		success:function (data) {
                    var logos = '';
                    for (var i in data.logos) {
                        logos += '<img style="height: 60px" src="'+CAMPANAS_URL+data.logos[i]+'" />';
                    }
		    var tips = data.tips || document.getElementById('noTipsTpl').innerHTML;
		    var images = (data.images)?'<ul id="fotos-list" class="box-list span">'+data.images+'</ul>':document.getElementById('noImagesTpl').innerHTML;
		    var favorito = (data.favorito)?'remover':'agregar';
		    detallesMarkerTpl = detallesMarkerTpl.replace(/\$\{markerNombre\}/g, data.marker.nombre)
		    .replace(/\$\{markerNombreUrl\}/g, marker.nombreUrl)
		    .replace(/\$\{markerCategoriaUrl\}/g, marker.imagen)
		    .replace(/\$\{markerId\}/g, marker.id)
		    .replace(/\$\{markerTipo\}/g, data.marker.tipo)
		    .replace(/\$\{markerDireccion\}/g, data.marker.direccion)
		    .replace(/\$\{markerHorario\}/g, data.marker.horario)
                    .replace(/\$\{markerVisitas\}/g, data.marker.visitas)
		    .replace(/\$\{markerTelefono\}/g, data.marker.telefono)
                    .replace(/\$\{markerFacebook\}/g, data.marker.fb)
                    .replace(/\$\{markerTwitter\}/g, data.marker.tw)
                    .replace(/\$\{markerWeb\}/g, data.marker.web)
                    .replace(/\$\{markerEmail\}/g, data.marker.email)
		    .replace(/\$\{markerDescripcion\}/g, data.marker.descripcion)
		    .replace(/\$\{markerFavoritos\}/g, data.marker.favoritos)
		    .replace(/\$\{markerTips\}/g, data.marker.tips)
		    .replace(/\$\{tips\}/g, tips)
		    .replace(/\$\{images\}/g, images)
                    .replace(/\$\{logos\}/g, logos)
		    .replace(/\$\{isFavorito\}/g, favorito)
		    .replace(/\$\{reciben\}/g, mapaController.classyCategories.create(data.marker.categoriasToIds, self.defs.categorias))
		    .replace(/\$\{[a-zA-Z]+\}/g, '');
		    scriptsController.loader.remove($('#marker-details-container header .wait'));
		    $('#marker-details-container article').html(detallesMarkerTpl).slideDown(600, function(){
                        $('#marker-menu-container').height($(this).outerHeight()-5);
		    });
		    mapaController.comentManager.init();
		    mapaController.favoritoManager.init(marker.id);
                    mapaController.denunciarManager.init(marker);
		    mapaController.imagesUploader.init(marker.id);
                    mapaController.fancybox.init();
		    FB.XFBML.parse();
		    $('#twbtn iframe, #twbtn .twitter-share-button').remove();
		    $('#twbtn').append('<a href="https://twitter.com/share" class="twitter-share-button" data-text="Donde Reciclo - '+marker.nombre+'" data-url="'+scriptsController.defs.baseUrl+'mapa/recicladora/'+marker.nombreUrl+'/'+marker.imagen+'/'+marker.id+'" data-lang="es">Twittear</a>')
		    twttr.widgets.load();
                    
                    if (!data.marker.descripcion)$('#description-item').remove();
                    if (!data.marker.fb)$('#fb-item').remove();
                    if (!data.marker.tw)$('#tw-item').remove();
                    if (!data.marker.telefono)$('#phone-item').remove();
                    if (!data.marker.web)$('#web-item').remove();
                    if (!data.marker.email)$('#email-item').remove();
                    if (!data.marker.horario)$('#hour-item').remove();
                    if (!data.marker.tipo)$('#marker-tipo').remove();
                    if (data.logos[0] == null)$('#logos-row').remove();
		}
	    });
	},

	//funcion para actualizar la url
	actualizarHash: function () {
	    var self = this;
	    var hash = '';
	    var titulo = 'Reciclado de ';
	    $('#category-list li .active').each(function () {
		var id = $(this).attr('id').slice(9);
		hash += self.defs.categorias[id].identificador+'/';
		titulo += self.defs.categorias[id].nombre+' ';

	    })
	    hash = hash.slice(0, hash.length-1);
	    if (navigator.appName == "Microsoft Internet Explorer") {//si es explorer
		if (window.location.href.indexOf('#') == -1) {
		    document.location = self.defs.baseUrl+'mapa/#!/'+hash;
		} else {
		    document.location.hash = '#!/'+hash;
		}
	    } else {//si es otro navegador
		window.history.replaceState('', titulo, self.defs.baseUrl+'mapa/'+hash);
	    }
	},

	changeUrlBymarker:function (marker) {
	    var self = this;
	    var hash = marker.nombreUrl+'/'+marker.imagen+'/'+marker.id;
	    document.getElementById('markerId').value = marker.id
	    if (navigator.appName == "Microsoft Internet Explorer") {//si es explorer
		if (window.location.href.indexOf('#') == -1) {
		    document.location = self.defs.baseUrl+'mapa/#!/recicladora/'+hash;
		} else {
		    document.location.hash = '#!/recicladora/'+hash;
		}
	    } else {//si es otro navegador
		window.history.replaceState('', marker.nombre, self.defs.baseUrl+'mapa/recicladora/'+hash);
	    }
	},

	init: function (categorias) {
	    this.setCategorias(categorias);
	    this.defs.map = new google.maps.Map(this.defs.mapContainer, this.defs.options);
	    this.defs.map.setCenter(this.defs.center);
	    if(!this.defs.urlMarker)mapaController.geolocation.init();
	    $myControl = document.getElementById('category-list-container');
	    $myControl.index = -500;
	    this.defs.map.controls[google.maps.ControlPosition.TOP_LEFT].push($myControl);
	    this.dynamicUrlParser();
            //mapaController.infoPopover.init();
	//buscadorMapa.init();
	}
    },

    sliderBox: {
	defs: {
	    categoryListContainer:$('#sliderBox').find('#category-list-container'),
	    isOpen:true
	},
	init: function () {
	    this.defs.isOpen = true;
	    this.bind();
	},
	moving: function () {
	    var move = (window.innerWidth < 767) ? 270 : 140,
	    obj = {
		'marginLeft': ''
	    };

	    if (mapaController.sliderBox.defs.isOpen) {
		$(this).addClass('active');
		move = '-='+move+'px';
		mapaController.sliderBox.defs.isOpen = false;
	    } else {
		$(this).removeClass('active');
		move = '+='+move+'px';
		mapaController.sliderBox.defs.isOpen = true;
	    }

	    if (window.innerWidth < 767) {
		obj = {
		    'marginTop': move
		}
	    } else {
		obj = {
		    'marginLeft': move
		}
	    }

	    mapaController.sliderBox.defs.categoryListContainer.animate(obj, {
		duration: 500,
		step: function() {
		    google.maps.event.trigger(mapaController.map.defs.map, 'resize');
		}
	    });
	},
	bind: function () {
	    $('#btn-expand-markers-list').live('click', this.moving);
	    if(window.innerWidth < 767) {
		this.defs.categoryListContainer.find('a').live('click', this.moving);
	    }
	}
    },

    infobox:{
	defs:{
	    tpl:document.getElementById('infoboxContent')
	},
	options: {
	    content: '',
	    disableAutoPan: false,
	    maxWidth: 0,
	    pixelOffset: new google.maps.Size(15, -68),
	    zIndex: null,
	    closeBoxURL: '',
	    infoBoxClearance: new google.maps.Size(1, 1),
	    isHidden: false,
	    pane: 'floatPane',
	    enableEventPropagation: false
	},
	createInfoboxHtml: function (marker) {
	    var content = this.defs.tpl.value.replace(/\$\{markerNombre\}/g, marker.nombre)
	    .replace(/\$\{markerDireccion\}/g, marker.direccion)
	    .replace(/\$\{markerImagen\}/g, marker.imagen)
	    .replace(/\$\{categoriasToString\}/g, marker.categoriasToString)
	    .replace(/\$\{[a-zA-Z]+\}/g, ''),
	    container = document.createElement('div'),
	    target = document.createElement('div');

	    target.className = 'target';

	    container.className = 'infobox';
	    container.innerHTML = content;
	    container.appendChild(target);

	    return {
		container: container,
		target: target
	    }
	},
	bindMarker: function (mapa, marker) {
	    var self = this,
	    infobox = new InfoBox(self.options),
	    infoboxHtml = self.createInfoboxHtml(marker);

	    infobox.setContent(infoboxHtml.container);
	    marker.infobox = infobox;

	    google.maps.event.addListener(marker, "mouseover", function (e) {
		if (self.currentInfobox != undefined) self.currentInfobox.close();
		marker.infobox.open(mapa, marker);
		self.currentInfobox = marker.infobox;
	    });
	    google.maps.event.addListener(marker, "mouseout", function (e) {
		marker.infobox.close()
	    });
	}
    },

    favoritoManager: {
	init: function (markerId) {
	    this.bind(markerId)
	},
	bind: function (markerId) {
	    var self = this,
	    favorito = document.getElementById('favorito'),
	    isFavorito = document.getElementById('isFavorito');

	    if (favorito) {
		favorito.onclick = function () {
		    favorito.onclick = null;
		    var accion = (isFavorito.innerHTML == 'agregar') ? 'add' : 'remove';
                    scriptsController.fixedLoader.show();
                    $.ajax({
			url: scriptsController.defs.baseUrl+'controllers/favoritoController/'+accion+'/marker/'+markerId,
                        beforeSend: function () {
                            scriptsController.fixedLoader.show();
                        },
			success: function (data) {
			    isFavorito.innerHTML = (isFavorito.innerHTML == 'agregar') ? 'remover' : 'agregar';
			    self.bind(markerId);
                            scriptsController.fixedLoader.hide();
			}
		    })
		}
	    }
	}
    },
    
    denunciarManager: {
        load:false,
	init: function (marker) {
            if (!this.load) {
                $("#comentario").countdown({
                    "max": 233,
                    "plural": "# caracteres restantes.",
                    "singular": "# caracter restante."
                });
                this.load = true;
            }
            this.bind(marker)
	},
	bind: function (marker) {
	    var self = this,
	    denunciar = document.getElementById('denunciar');
            if (denunciar) {
		denunciar.onclick = function () {
                    $('#denunciarMarkerNombre').html(marker.nombre);
                    $('#denunciarMarkerDireccion').html(marker.direccion);
                    $("#comentario").val('')
                    $('#denunciarModal').modal('show');
                    self.bindForm(marker);
		}
	    }
	},
        bindForm: function (marker) {
            var submit = document.getElementById('denunciarSubmit');
            $('#denunciarFomrContainer').show();
            $('#denunciarLoader').hide();
            submit.onclick = function () {
                $.ajax({
                    data:$('#denunciarForm').serialize(),
                    type:'post',
                    url: scriptsController.defs.baseUrl+'controllers/denunciaController/denunciar/marker/'+marker.id,
                    beforeSend: function () {
                        $('#denunciarFomrContainer').hide();
                        $('#denunciarLoader').show();
                    },
                    success: function (data) {
                        $('#denunciarLoader').html('<p>Gracias por colaborar con Donde Reciclo.');
                    }
                })
            }
        }
    },

    comentManager : {
	init: function () {
	    this.bind();
	},
	bind: function () {
	    $("#comment-field").countdown({
		"max": 144,
		"plural": "# caracteres restantes.",
		"singular": "# caracter restante."
	    });
	    var enviador = document.getElementById('btn-send-comment');
	    if (enviador) {
		enviador.onclick = function () {
		    var comentario = document.getElementById('comment-field').value,
		    markerId = document.getElementById('markerId').value,
		    tipTpl = document.getElementById('tipTpl').innerHTML,
		    current = this;

		    current.className += ' disabled'
		    current.innerHTML = 'Espere...';

		    $.ajax({
			url: scriptsController.defs.baseUrl+'controllers/comentarioController/tip/',
			data: 'comentario='+comentario+'&markerId='+markerId,
			type: 'post',
			success:function (data) {
			    current.innerHTML = 'Enviar';
			    current.className = current.className.replace(' disabled', '');
			    tipTpl = tipTpl.replace(/\$\{owner}/g, data)
			    .replace(/\$\{comentario\}/g, comentario)
			    document.getElementById('tips-list').innerHTML = tipTpl+document.getElementById('tips-list').innerHTML;
			}
		    });
		    return false;
		}
	    }
	}
    },

    imagesUploader: {
	defs: {
	    time: null
	},
	init: function (markerId) {
	    var boton = document.getElementById('fileuploader');

	    if (boton) {
		var self = this,
		d = new Date();

		self.defs.time = Math.floor((d.getTime()/1000));

		new qq.FileUploader({
		    element: boton,
		    action: scriptsController.defs.baseUrl+'controllers/imagesController/upload/',
		    allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
		    sizeLimit: 1 * 1024 * 1024,
		    params: {
			objectId:markerId,
			time:self.defs.time
		    },
		    messages: {
			typeError: "{file} es de un formato no permitido. Estos son los formatos permitidos: {extensions}.",
			sizeError: "{file} es muy pesado, el m&aacuteximo permitido es de {sizeLimit}.",
			onLeave: "Hay archivos que todav&iacute; no se cargaron. Si dej&aacute; la p&aacute;gina no se van a cargar con &eacute;xito."
		    },
		    showMessage: function(message){
			alert(message);
		    },
		    onComplete: function(id, fileName, responseJSON){
                        if(responseJSON.success)$('#cargarFotos').show();
		    }
		});
                this.stylize();
		this.bind(markerId);
	    }
	},
	bind: function (markerId) {
	    var self = this;

	    document.getElementById('cargarFotos').onclick = function () {
		this.parentNode.removeChild(this);

		document.getElementById('fileuploader').parentNode.removeChild(document.getElementById('fileuploader'))
		document.getElementById('noImages').innerHTML = '<ul id="fotos-list" class="box-list span">';
		scriptsController.loader.append($('#fotos-row .wait'), 'medium');

		$.ajax({
		    url: scriptsController.defs.baseUrl+'controllers/imagesController/save/'+self.defs.time+'/'+markerId,
		    success: function (data) {
			document.getElementById('fotos-list').innerHTML = data +document.getElementById('fotos-list').innerHTML;
			scriptsController.loader.remove($('#fotos-row .wait'));
		    }
		});
	    }
	},
        stylize: function () {
            $('.qq-upload-drop-area').remove();
            $('.qq-upload-button').css({background:'none', color:'#464646', fontSize:'12px', border:'none', width:'168px', padding:0});
            $('.qq-upload-button').contents().eq(0).wrap('<p />').parent().text('Suma tu foto a este punto').contents().unwrap();
            $('.qq-upload-button').prepend('<span class="icons icons-panel icon-add-image" style="width:18px; height:18px; margin: 0 10px 0 0;"></span>')
        }
    },

    geolocation: {
	defs: {
	    browserSupportFlag: null,
	    initialLocation: null
	},
	init : function () {
	    var self = this;

	    if(navigator.geolocation) {
		self.browserSupportFlag = true;
		navigator.geolocation.getCurrentPosition(
		    function(position) {
			self.initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
			mapaController.map.defs.map.setCenter(self.initialLocation);
		    },
		    function() {
		    //handleNoGeoLocation(browserSupportFlag);
		    });
	    } else if (google.gears) { // Try Google Gears Geolocation
		self.browserSupportFlag = true;
		var geo = google.gears.factory.create('beta.geolocation');
		geo.getCurrentPosition(
		    function(position) {
			self.initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
			mapaController.map.defs.map.setCenter(self.initialLocation);
		    },
		    function() {
		    //handleNoGeoLocation(browserSupportFlag);
		    });
	    } else { // Browser doesn't support Geolocation
		map.setCenter(mapaController.map.defs.center);
	    }
	}
    },

    classyCategories: {
	create: function (c, ctgs) {
	    c = c.split(',');
	    var html = '';
	    for (var i=0, l=c.length; i<l; i++) {
		html += '<em class="recive-item '+ctgs[c[i]].identificador+'-item label"><span class="bg-color"></span><span class="val">'+ctgs[c[i]].nombre+'</span></em>';
	    }
	    return html;
	}
    },
    
    infoPopover: {
        init: function () {
            if (mapaController.coockieHelper.getCookie('infoPopover'))return false;
            $('#mapa-search-input').popover({
                html:true,
                title: '\u00BFC\u00F3mo usar Donde Reciclo?',
                content: '\
                    <p>Busca la direcci&oacute;n o el barrio en donde te encuentras<p>\
                    <p>&nbsp;</p>\
                    <p style="text-align:right"><a href="javascript:void(0);" id="infoPopover1" class="btn btn-mini btn-info">Siguiente</a></p>\
                ',
                placement: 'bottom'
            });
            $('#category-list li:eq(6)').popover({
                html:true,
                title: '\u00BFC\u00F3mo usar Donde Reciclo?',
                content: '\
                    <p>Elige el material que deseas reciclar</p>\
                    <p style="text-align:right"><a href="javascript:void(0);" id="infoPopover2" class="btn btn-mini btn-info">Siguiente</a></p>\
                ',
                placement: 'right'
            });
            $('#mapa-box').popover({
                html:true,
                title: '\u00BFC\u00F3mo usar Donde Reciclo?',
                content: '\
                    <p><img src="'+scriptsController.defs.baseUrl+'resources/img/markers/generic.png" align="left" style="margin-right: 5px">Haz click en los markers para obtener m&aacute;s informaci&oacute;n</p>\
                    <p style="text-align:right"><a href="javascript:void(0);" id="infoPopover3" class="btn btn-mini btn-info">Fin</a></p>\
                ',
                placement: 'top'
            });
            $('#mapa-search-input').popover('show');
            this.bind1();
            mapaController.coockieHelper.setCookie('infoPopover', 'true')
        },
        bind1: function () {
            var self = this;
            $('#infoPopover1').click(function () {
                $('#mapa-search-input').popover('hide');
                $('#category-list li:eq(6)').popover('show');
                self.bind2();
            })
            $('#mapa-search-input, #category-list li:eq(6), #mapa-box').unbind('mouseenter').unbind('mouseleave');
        },
        bind2: function () {
            var self = this;
            $('#infoPopover2').click(function () {
                $('#category-list li:eq(6)').popover('hide');
                $('#mapa-box').popover('show');
                self.bind3();
            })
        },
        bind3: function () {
            $('#infoPopover3').click(function () {
                $('#mapa-box').popover('hide');
            })
        }
    },
    
    coockieHelper: {
        setCookie: function (nombre,valor,dias) {
            var vencimiento = new Date();
            vencimiento.setDate(vencimiento.getDate() + dias);
            valor = escape(valor) + ((dias==null) ? "" : "; expires="+vencimiento.toUTCString());
            document.cookie = nombre + "=" + valor;
        },
        getCookie: function (nombre) {
            var i,x,y,ARRcookies=document.cookie.split(";");
            for (i=0;i<ARRcookies.length;i++) {
                x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
                y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
                x=x.replace(/^\s+|\s+$/g,"");
                if (x==nombre) {
                    return unescape(y);
                }
            }
            return false;
        }
    },
    
    tallyCounter: {
        addVisitante: function (i) {
            if (!mapaController.coockieHelper.getCookie('marker-'+i)) {
                $.ajax({
                    url: scriptsController.defs.baseUrl+'controllers/markerController/addVisitante/'+i
                })
                mapaController.coockieHelper.setCookie('marker-'+i, 'true', 1);
            }
        }
    },
    
    fancybox: {
        init: function () {
            $(".fancybox").fancybox({
		openEffect	: 'none',
		closeEffect	: 'none'
            });
        }
    },

    init: function(){
	this.expandMapComponent.init();
	this.scrollToComponent.init();
	this.markersListComponent.init();
	this.getContent.init();
	//this.usuario.init(); esto no se porque estaba aca, lo comente porque da error (maxi, 04-04-2013)
    //this.map.init(); El mapa se inicia despues de cargar el contenido de las categorias via ajax
    //por eso se llama a su init en el success de getContent.get
    }
}

$(function(){
    FB.init({
        appId:'321221204603640',
        status:true, 
        cookie:true,
        FBxfbml:true,
        oauth:true
    });
    mapaController.init();
});

function Categoria () {
    this.markers = new Array ();
    this.identificador = new String ();
    this.nombre = new String ();
}